import {
  userCollection,
  log
} from '../share/index'
import uniToken from './uni-token'
import {
  verifyCode
} from './verify'
import loginCheck from '../common/login-check'

async function loginBySms ({
  mobile,
  code
}) {
  const verifyRes = await verifyCode({
    mobile,
    code,
    type: 'login'
  })
  if (verifyRes.code !== 0) {
    return verifyRes // 验证失败
  }
  const query = {
    mobile,
    mobile_confirmed: 1
  }
  const userInDB = await userCollection.where(query).get()

  log('userInDB:', userInDB)

  if (userInDB && userInDB.data && userInDB.data.length > 0) {
    const userMatched = userInDB.data[0]
    try {
      const loginCheckRes = await loginCheck(userMatched)
      if (loginCheckRes.code !== 0) {
        return loginCheckRes
      }
      const tokenList = loginCheckRes.user.token

      log('开始修改最后登录时间')

      const {
        token,
        tokenExpired
      } = uniToken.createToken(userMatched)
      log('token', token)
      tokenList.push(token)
      const upRes = await userCollection.doc(userMatched._id).update({
        last_login_date: new Date().getTime(),
        last_login_ip: __ctx__.CLIENTIP,
        token: tokenList
      })

      log('upRes', upRes)

      return {
        code: 0,
        token: token,
        uid: userMatched._id,
        username: userMatched.username,
        mobile,
        msg: '登录成功',
        tokenExpired: tokenExpired
      }
    } catch (e) {
      log('写入异常：', e)
      return {
        code: 90001,
        msg: '数据库写入异常'
      }
    }
  } else {
    // 注册用户
    const user = {
      mobile: mobile,
      mobile_confirmed: 1,
      register_ip: __ctx__.CLIENTIP,
      register_date: Date.now()
    }
    const addRes = await userCollection.add(user)
    log('addRes', addRes)
    const uid = addRes.id

    if (addRes.id) {
      const {
        token,
        tokenExpired
      } = uniToken.createToken({
        _id: uid
      })
      await userCollection.doc(uid).update({
        token: [token]
      })
      return {
        code: 0,
        uid,
        mobile,
        msg: '注册成功',
        token,
        tokenExpired
      }
    }
    return {
      code: 90001,
      msg: '数据库写入失败'
    }
  }
}

export default loginBySms
